package com.thinkgsp.report;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import com.thinkgsp.jxc.model.Bill;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.JRRewindableDataSource;

public class JRBillDataSource implements JRRewindableDataSource {

	private Bill bill;
	
	public JRBillDataSource(Bill bill) {
		if(bill == null) {
			throw new ReportException("单据对象不能空。");
		}
		if(bill.getDetails() == null || bill.getDetails().size() == 0) {
			throw new ReportException("单据明细不能空。");
		}
		bill.setDetailIndex(-1);
		this.bill = bill;
	}

	public Object getFieldValue(JRField field) throws JRException {
		try {
			String val = BeanUtils.getProperty(bill, field.getDescription());
			if(val==null)
				return null;
			return ConvertUtils.convert(val, field.getValueClass());
		} catch(Exception e) {
			throw new ReportException("获取数据源数据失败：" + field.getDescription());
		}
	}

	public boolean next() throws JRException {
		bill.setDetailIndex(bill.getDetailIndex() + 1);
		return bill.getDetailIndex() < bill.getDetails().size();
	}

	public void moveFirst() throws JRException {
		bill.setDetailIndex(0);
	}

}
